/**
 * Created by zhangchuanguo on 2017/06/19
 */


var util = require('../utils/util');
var mconferenceClass = require('../class/mconference');
var daoUtil = require('../utils/daoUtil');
var stockRecommend = require('../controller/controller.stockrecommend');

module.exports = {

    create: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var mconference = new mconferenceClass();
        /**
         *
         */
        params.companyRecommend = '0';
        var analystType = params.analystType;
        if (analystType == 'company') {
            params.companyRecommend = '1';
        }
        var checkResult = mconference.checkParams(
            [
                'industry',
                'date',
                'type',
                'corePoint',
                'analyst'
            ],
            params);
        if (checkResult) {
            cb(util.getErrorRes('400', checkResult), null);
            return;
        } else {
            mconference.init(params);
        }
        var analystType = params.analystType;

        models.mconference.findOrCreate(mconference.getParams(), function (err, data) {
            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            var actionId = data.rowId;
            if (analystType == 'company') {
                var stockList = params.stockList;

                for (var i = 0; i < stockList.length; i++) {

                    stockList[i].actionId = actionId;
                    stockList[i].actionType="mconference";

                }
                stockRecommend.create(stockList, function (err, result) {
                    if (err) {
                        cb(util.getErrorRes(err));
                    }else {
                        data.companyRecommend = result;
                        cb(null, util.getSuccessRes(data));
                    }
                });
            } else {
                cb(null, util.getSuccessRes(data));
            }

        });
    },
    checkOne:function(params, cb) {
        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var mconference = new mconferenceClass();
        params.status = 1;
        mconference.init(params);


        models.mconference.find(mconference.getParams()).exec(function (err, data) {
            if (err) {
                console.log(err);
                // return res.serverError(err);
            }
            cb(null, util.getSuccessRes(data));
        });
    },
    update: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var mconference = new mconferenceClass();
        params.companyRecommend = '0';
        var analystType = params.analystType;
        if (analystType == 'company') {
            params.companyRecommend = '1';
        }
        var checkResult = mconference.checkParams(
            [   'rowId',
                'industry',
                'date',
                'type',
                'corePoint',
                'analyst'
            ],
            params);
        if (checkResult) {
            cb(util.getErrorRes('400', checkResult), null);
            return;
        } else {
            mconference.init(params);
        }

        models.mconference.update({rowId: params.rowId}, mconference.getParams()).exec(function (err, data) {
            if (err || !data) {
                console.log(err);
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            var actionId = params.rowId;
            if (analystType == 'company') {
                var stockList = params.stockList;

                for (var i = 0; i < stockList.length; i++) {

                    stockList[i].actionId = actionId;
                    stockList[i].actionType="mconference";
                }
                stockRecommend.deleteByActionId({"actionId":params.rowId}, function (err, result) {
                    if (err) {
                        handleError(res, err);
                    }else{
                        stockRecommend.create(stockList, function (err, result) {
                            if (err) {
                                handleError(res, err);
                            } else {
                                data.companyRecommend = result;
                                cb(null, util.getSuccessRes(data));
                            }
                        });
                    }
                });

            } else {
                stockRecommend.deleteByActionId({"actionId":params.rowId}, function (err, result) {
                    if (err) {
                        handleError(res, err);
                    }else{
                        cb(null, util.getSuccessRes(data));
                    }
                });
            }
        });
    },
    /**
     * 软删除
     * @param params
     * @param cb
     */
    delete:function (params, cb) {
        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var mconference = new mconferenceClass();

        var checkResult = mconference.checkParams(['rowId'], params);
        if (checkResult) {
            cb(util.getErrorRes('400', checkResult), null);
            return;
        } else {
            params.status='0';
            mconference.init(params);
        }


        models.mconference.update({rowId: params.rowId}, mconference.getParams()).exec(function (err, data) {
            if (err || !data) {
                console.log(err);
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });


    },
    getInfo: function (params, cb) {
        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var mconference = new mconferenceClass();

        var checkResult = mconference.checkParams(['rowId'], params);
        if (checkResult) {
            cb(util.getErrorRes('400', checkResult), null);
            return;
        } else {
            mconference.init(params);
        }

        models.mconference.findOne(mconference.getParams()).populate('comments',{sort: 'createdAt desc'}).populate('createUid').populate('analyst').populate('industry').exec(function (err, data) {
            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            var companyRecommend = data.companyRecommend;
            if (companyRecommend == '1') {
                stockRecommend.getListByActionId({actionId:data.rowId}, function (err, result) {
                    if (err) {
                        cb(res, err);
                    } else {
                        data.companyRecommend = result.obj;
                        cb(null, util.getSuccessRes(data));
                    }
                })
            } else {
                cb(null, util.getSuccessRes(data));
            }
        });
    },

    getListBySeller: function (params, cb) {

        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var mconference = new mconferenceClass();

        var checkResult = mconference.checkParams(['seller'], params);
        if (checkResult) {
            cb(util.getErrorRes('400', checkResult), null);
            return;
        } else {
            mconference.init(params);
        }


        models.mconference.find(mconference.getParams()).populate('seller').populate('analyst').populate('industry').exec(function (err, data) {
            if (err) {
                console.log(err);
                // return res.serverError(err);
            }
            cb(null, util.getSuccessRes(data));
        });
    },

    getList: function (params, cb) {

        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var mconference = new mconferenceClass();
        var resData = null;
        mconference.init(params);
        var sql = "select c.* from (select a.*,max(b.createdAt)btime from tb_mconference a left join tb_comment b on a.rowId = b.mconference and b.enable = 1 where a.date ='"+params.date+"'   group by a.rowId)c  group by c.rowId order by c.btime desc";
        models.mconference.query(sql,function (err, descData) {
            if (err || !descData) {
                console.error(err);
                cb(util.getSysError());
            }else{
                resData = descData.length==0 ? []:[descData.length];
                models.mconference.find(mconference.getParams()).populate('comments',{enable:1,sort: 'createdAt desc'}).populate('recommends').populate('analyst').populate('industry').exec(function (err, data) {
                    if (err) {
                        return res.serverError(err);
                    }

                    for (var i in data) {
                        for(var j in descData){
                            if(data[i].rowId == descData[j].rowid){
                                resData[j] = data[i];
                            }
                        }
                    }
                    cb(null, util.getSuccessRes(resData));
                });
            }

        });

    },
    getMorningconferenceCount:function(params, cb){
        var that = this;
        var validate = daoUtil.validate(['startDate','endDate','type'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            var sql = "select a.comment,b.name,b.morning from (select count(rowId) comment,name,createUid from tb_comment where type = '"+params.type+"' and enable = 1 and createdAt >='"+params.startDate+"' and createdAt <='"+params.endDate+"' group by name )a right JOIN " +
                "(select count(m.rowId) morning,u.rowId,u.name  from tb_mconference m right JOIN tb_user u on m.createUid = u.rowId and m.date >='"+params.startDate+"' and m.date <='"+params.endDate+"'and  m.status = 1 and u.enable = 1 where u.name not in ('王金杰','qiang','ding','周健','邱阳','杨智')   group by u.rowId) b on a.createUid = b.rowId order by b.morning asc,a.comment asc";
            models.mconference.query(sql,function (err, data) {
                if (err || !data) {
                    console.error(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },

    getListByRowIds: function (params, cb) {

        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }

        var expr = {rowId: params};

        models.mconference.find(expr).populate('seller').populate('analyst').populate('industry').exec(function (err, data) {
            if (err) {
                cb(err, null);
            }
            cb(null, util.getSuccessRes(data));
        });
    }

};



